package com.xhwl.logistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.dao.VehcAreaDao;
import com.xhwl.logistics.dao.VehcCarSpotDao;
import com.xhwl.logistics.dao.VehcParkingLotDao;
import com.xhwl.logistics.enums.VehicleCodeEnum;
import com.xhwl.common.enums.vehicle.SpotTypeEnum;
import com.xhwl.common.pojo.cent.vehicle.VehcArea;
import com.xhwl.common.pojo.cent.vehicle.VehcCarSpot;
import com.xhwl.common.pojo.cent.vehicle.VehcParkingLot;
import com.xhwl.common.query.cent.vehicle.CarSpotQuery;
import com.xhwl.logistics.service.cent.IOrganizationService;
import com.xhwl.logistics.service.cent.IProjectService;
import com.xhwl.logistics.service.IVehcCarSpotService;
import com.xhwl.common.vo.cent.vehicle.CarSpotVO;
import com.xhwl.logistics.service.cent.QueryDeviceService;
import com.xhwl.logistics.strategy.impl.VehicleParkingLotHuaWeiIOTHandlerImpl;
import com.xhwl.logistics.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lu.Aaron
 * @since 2021-02-08
 */
@Slf4j
//@Service
public class VehcCarSpotServiceImpl extends ServiceImpl<VehcCarSpotDao, VehcCarSpot> implements IVehcCarSpotService {
    @Autowired
    private VehcCarSpotDao vehcCarSpotDao;
    @Autowired
    private VehcAreaDao vehcAreaDao;
    @Autowired
    private QueryDeviceService queryDeviceService;
    @Autowired
    private VehcParkingLotDao vehcParkingLotDao;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private VehicleParkingLotHuaWeiIOTHandlerImpl vehicleParkingLotHuaWeiIOTHandler;

    @Override
    public void add(CarSpotVO carSpotVO, Short industryId) {
        //TODO 根据String syncManufacturer = carSpotVO.getSyncManufacturer()判断选择供应商，同步数据;
        //TODO 若syncManufacturer空，通过项目查询供应商，在进行同步数据
        VehcCarSpot vcs = vehcCarSpotDao.selectOne(new QueryWrapper<VehcCarSpot>().eq("number", carSpotVO.getNumber()).eq("parking_lot_id",carSpotVO.getParkingLotId()));
        if (null!=vcs) {
            throw new BusinessException("编号不能重复");
        }
        if (null==carSpotVO.getAreaOrgId()) {
            throw new BusinessException("缺少必要参数：areaOrgId");
        }
        if (null==carSpotVO.getEnterpriseId()) {
            throw new BusinessException("缺少必要参数：enterpriseId");
        }
        if (null==carSpotVO.getLevel()) {
            throw new BusinessException("缺少必要项目层级数参数：level");
        }
        //TODO 1.调用主数据服务，在sdata_organization表新增车位
        Organization organization = new Organization();
        organization.setParentId(carSpotVO.getAreaOrgId());
        organization.setEnterpriseId(carSpotVO.getEnterpriseId());
        organization.setName(carSpotVO.getNumber());
        //如果用户选择无区域，则areaOrgId为parkingLotId对应的OrgId.层级则为4 否则为5
        if (null==carSpotVO.getAreaId()) {
            organization.setLevel(carSpotVO.getLevel()+2);
        }else{
            organization.setLevel(carSpotVO.getLevel()+3);
        }

        organization.setIndustryId(industryId);

        //cent-common修改Organization setType
        organization.setType(OrganizationTypeEnum.CAR_SPOT.getId().intValue());

        ResultJson<Integer> resultJson = organizationService.create(organization, new Account());
        Integer orgId = resultJson.getResult();
        //TODO 2.新增车位
        VehcCarSpot vehcCarSpot = new VehcCarSpot();
        BeanUtils.copyProperties(carSpotVO,vehcCarSpot);
        vehcCarSpot.setOrgId(orgId);
        vehcCarSpotDao.insert(vehcCarSpot);

    }

    @Override
    public void edit(CarSpotVO carSpotVO, Short industryId) {
        //TODO 根据String syncManufacturer = carSpotVO.getSyncManufacturer()判断选择供应商，同步数据;
        //TODO 若syncManufacturer空，通过项目查询供应商，在进行同步数据
        Integer id = carSpotVO.getId();
        if (null==id) {
            throw new BusinessException(VehicleCodeEnum.ID_NO_EXIST.description);
        }
        VehcCarSpot vcs = vehcCarSpotDao.selectOne(new QueryWrapper<VehcCarSpot>().eq("number", carSpotVO.getNumber()).ne("id",carSpotVO.getId()).eq("parking_lot_id",carSpotVO.getParkingLotId()));
        if (null!=vcs) {
            throw new BusinessException("编号不能重复");
        }
        if (Objects.isNull(carSpotVO.getOrgId())) {
            throw new BusinessException("缺少必要参数：orgId");
        }
        if (null==carSpotVO.getAreaOrgId()) {
            throw new BusinessException("缺少必要参数：areaOrgId");
        }
        if (null==carSpotVO.getEnterpriseId()) {
            throw new BusinessException("缺少必要参数：enterpriseId");
        }
        if (null==carSpotVO.getLevel()) {
            throw new BusinessException("缺少必要项目层级数参数：level");
        }
        //TODO 1.调用主数据服务，在sdata_organization表修改车位
        Organization organization = new Organization();
        organization.setId(carSpotVO.getOrgId());
        organization.setParentId(carSpotVO.getAreaOrgId());
        //如果用户选择无区域，则areaOrgId为parkingLotId对应的OrgId.层级则为4 否则为5
        if (null==carSpotVO.getAreaId()) {
            organization.setLevel(carSpotVO.getLevel()+2);
        }else{
            organization.setLevel(carSpotVO.getLevel()+3);
        }
        organization.setIndustryId(industryId);
        organization.setName(carSpotVO.getNumber());
        organization.setEnterpriseId(carSpotVO.getEnterpriseId());

        //cent-common修改Organization setType
        organization.setType(OrganizationTypeEnum.CAR_SPOT.getId().intValue());

        organizationService.update(organization, new Account());
        //TODO 2.修改车位
        VehcCarSpot vehcCarSpot = new VehcCarSpot();
        BeanUtils.copyProperties(carSpotVO,vehcCarSpot);
        vehcCarSpotDao.updateById(vehcCarSpot);
    }

    @Override
    public void delete(Integer id, Short industryId) {
        //TODO 通过id查询对应的projectId再查询对应的供应商
        //TODO 1.调用主数据服务，在sdata_organization表删除车位
        VehcCarSpot vehcCarSpot = vehcCarSpotDao.selectById(id);
        organizationService.delete(vehcCarSpot.getOrgId(), null);
        //TODO 2.删除车位
        vehcCarSpotDao.deleteById(id);
    }

    @Override
    public ResultJson numberCheck(String number, Integer parkingLotId) {
        VehcCarSpot vehcCarSpot = vehcCarSpotDao.selectOne(new QueryWrapper<VehcCarSpot>().eq("number", number).eq("parking_lot_id",parkingLotId));
        if (null==vehcCarSpot) {
            //未存在
            return  new ResultJson(true, CodeEnum.SUCCESS.getCode(),"该编号可使用");

        }else {
            //已存在
            return  new ResultJson(true, CodeEnum.FAIL.getCode(),"该编号不可用");
        }

    }
    @Override
    public Page<VehcCarSpot> carSpotPage( CarSpotQuery carSpotQuery) {
        //Integer projectId, Integer parkingLotId, String areaName, SpotTypeEnum type, Page page
        List<Integer> projectIds = carSpotQuery.getProjectIds();
        if (null==projectIds||projectIds.isEmpty()) {
            throw new BusinessException(VehicleCodeEnum.PROJECT_ID_LACK.description);
        }
        Integer parkingLotId = carSpotQuery.getParkingLotId();
        String areaName = carSpotQuery.getAreaName();
        SpotTypeEnum type = carSpotQuery.getType();
        Page<VehcCarSpot> page = new Page<>();
        page.setCurrent(carSpotQuery.getCurrent());
        page.setSize(carSpotQuery.getPageSize());
        QueryWrapper<VehcCarSpot> wrapper = new QueryWrapper<>();
        if (null!=projectIds&&!projectIds.isEmpty()) {
            wrapper.in("project_id",projectIds);
        }
        if (null!=parkingLotId) {
            wrapper.eq("parking_lot_id",parkingLotId);
        }

        if (StringUtils.isNotBlank(areaName)) {
            List<VehcArea> vehcAreas = vehcAreaDao.selectList(new QueryWrapper<VehcArea>().like("name", areaName));
            if (vehcAreas.isEmpty()) {
                //如果根据区域名称查询不到区域集合，则返回空
                return page;
            }else {
                List<Integer> areaIds = vehcAreas.stream().map(v -> v.getId()).collect(Collectors.toList());
                wrapper.in("area_id",areaIds);
            }

        }
        if (null!=type) {
            wrapper.eq("type",type);
        }
        wrapper.orderByDesc("id");
        Page<VehcCarSpot> vehcCarSpotPage = vehcCarSpotDao.selectPage(page, wrapper);
        List<VehcCarSpot> vehcCarSpots = vehcCarSpotPage.getRecords();
        if (!vehcCarSpots.isEmpty()) {
            //获取搜索列表的areaName和parkingLotName
            Set<Integer> parkingLotIds = vehcCarSpots.stream().map(v -> v.getParkingLotId()).collect(Collectors.toSet());
            Set<Integer> areaIds = vehcCarSpots.stream().map(v -> v.getAreaId()).collect(Collectors.toSet());
            List<VehcParkingLot> vehcParkingLots = vehcParkingLotDao.selectList(new QueryWrapper<VehcParkingLot>().in("id", parkingLotIds));
            List<VehcArea> vehcAreas = vehcAreaDao.selectList(new QueryWrapper<VehcArea>().in("id", areaIds));
            List<Integer> projectIds2 = vehcCarSpots.stream().map(v -> v.getProjectId()).collect(Collectors.toList());
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withIdList(projectIds2);
            List<Project> projects = projectService.list(projectQuery, null);
            vehcCarSpots.forEach(vcs->{
                vehcParkingLots.forEach(vpl->{
                    if (vpl.getId().equals(vcs.getParkingLotId())) {
                        vcs.setParkingLotName(vpl.getName());
                        vcs.setParkingLotOrgId(vpl.getOrgId());
                    }
                });
                vehcAreas.forEach(va->{
                    if (va.getId().equals(vcs.getAreaId())) {
                        vcs.setAreaName(va.getName());
                        vcs.setAreaOrgId(va.getOrgId());
                    }
                });
                ;



                projects.forEach(p->{
                    if (vcs.getProjectId().equals(p.getId())) {
                        vcs.setProjectName(p.getName());
                    }
                });
            });
        }


        return vehcCarSpotPage;
    }

    @Override
    public void statisticCarSpot() {
        List<VehicleIntegratedConfigBO> vehicleIntegratedConfigBOList = queryDeviceService.queryIntegratedConfigs();
        //获取金茂的信息
        VehicleIntegratedConfigBO vehicleIntegratedConfigBO = vehicleIntegratedConfigBOList.stream().filter(s -> {
            if(s.getVehicleSystemInfoBO().getProductId()!=null){
                if (s.getVehicleSystemInfoBO().getProductId() == 1) {
                    return true;
                }else {
                    return false;
                }
            }else {
                return false;
            }
        }).findAny().orElse(null);
        if(vehicleIntegratedConfigBO!=null){
            vehicleParkingLotHuaWeiIOTHandler.statisticsToBi(vehicleIntegratedConfigBO);
        }
    }
}
